#include <bits/stdc++.h>

using namespace std;

const int N = 1010;
typedef pair<int,int>PII;
char g[N][N];
int n , m;
int dx[] = {0 , 0 , 1 , -1};
int dy[] = {1 , -1 , 0 , 0};
int cid[N][N];
int csize[N * N];

queue<PII>q;
int bfs(int x , int y , int id)
{
    queue<PII>q;
    q.push({x , y});
    cid[x][y] = id;
    int size = 0;
    while(!q.empty())
    {
        auto [cx , cy] = q.front();
        q.pop();
        size ++;
        for(int k = 0;k < 4;k ++)
        {
            int nx = cx + dx[k] , ny = cy + dy[k];
            if(nx >= 1 && ny >= 1 && nx <= n && ny <= n
            && cid[nx][ny] == -1 && g[nx][ny] != g[cx][cy])
            {
                cid[nx][ny] = id;
                q.push({nx , ny});
            }
        }
    }
    return size;
}

int main()
{
    cin >> n >> m;
    for(int i = 1;i <= n;i ++)
        for(int j = 1;j <= n;j ++)
            cin >> g[i][j];

    memset(cid , -1 , sizeof cid);
    int cur_id = 0;
    for(int i = 1;i <= n;i ++)
        for(int j = 1;j <= n;j ++)
            if(cid[i][j] == -1)
            {
                csize[cur_id] = bfs(i , j , cur_id);
                cur_id ++;
            }

    while(m--)
    {
        int x , y;
        cin >> x >> y;
        cout << csize[cid[x][y]] << endl;
    }
    return 0;
}